<?php

namespace app\common\extract;

use PhpOffice\PhpWord\PhpWord;

class Word extends Extract
{
    protected $_phpword;
    protected $_text_arr;

    public function __construct()
    {
        $this->_phpword = new PhpWord();
    }

    public function template2File($filename, $args)
    {
        $document = $this->_phpword->loadTemplate(config('huisheng.view_template_meeting'));
        foreach ($args as $key => $value) {
            $document->setValue($key, $value);
        }
        $document->saveAs(config('huisheng.word_result') . $filename . ".docx");
        return config('huisheng.word_result') . $filename . ".docx";
    }

    public function getArray()
    {
        if (!$this->_file) {
            return [];
        }

        $file_data = $this->getWord($this->_file);
        //正则按标点分段
        $file_data = preg_split('/\！|\？|\。/',$file_data);
        return $file_data;
    }

    protected function getWord($file)
    {
        if (is_file($file)) {
            $this->_phpword = \PhpOffice\PhpWord\IOFactory::load($file);
            $_text_arr = $this->Text($this->_phpword, ($_text_arr = array()));
            $_text = implode("",$_text_arr);
            return $_text;
        }
        return '';
    }

    protected function Text($class, $arr)
    {
        switch (get_class($class)) {
            case 'PhpOffice\PhpWord\PhpWord':
                foreach ($class->getSections() as $element) {
                    $arr=$this->Text($element, $arr);
                }
                break;
            case 'PhpOffice\PhpWord\Element\Section':
                foreach ($class->getElements() as $element) {
                    $arr=$this->Text($element, $arr);
                }
                break;
            case 'PhpOffice\PhpWord\Element\TextBreak':
                break;
            case 'PhpOffice\PhpWord\Element\TextRun':
                foreach ($class->getElements() as $element) {
                    $arr=$this->Text($element, $arr);
                }
                break;
            case 'PhpOffice\PhpWord\Element\Text':
                $arr[] = $class->getText();
                break;
            default:
                break;
        }
        return $arr;
    }
}
